

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/icon.png">
  <link rel="icon" href="/img/icon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="d-lue">
  <meta name="keywords" content="">
  
    <meta name="description" content="默认全局环境ts默认是全局环境 – 模块化变为局部环境 123let a = 456;console.log(a);//a是全局变量  123456let a = 456;console.log(a);export &amp;#123;&amp;#125;/a是局部变量   声明空间类型声明空间 1type A = string // A的类型是字符串  变量声明空间 1let a = &amp;quot;abc&amp;quo">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>TS基础 - d-lue&#39; blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"dl_coisini.gitee.io","root":"/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"9c32ca7145bad202032b544e8bf27d19","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?9c32ca7145bad202032b544e8bf27d19";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>d-lue&#39;s blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/bg/wenzhang.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="TS基础"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-09-25 00:00" pubdate>
          2023年9月25日 凌晨
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          3.7k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          32 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">TS基础</h1>
            
            
              <div class="markdown-body">
                
                <h3 id="默认全局环境"><a href="#默认全局环境" class="headerlink" title="默认全局环境"></a>默认全局环境</h3><p>ts默认是全局环境 – 模块化变为局部环境</p>
<figure class="highlight abnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs abnf">let a <span class="hljs-operator">=</span> <span class="hljs-number">456</span><span class="hljs-comment">;</span><br>console.log(a)<span class="hljs-comment">;</span><br>//a是全局变量<br></code></pre></td></tr></table></figure>

<figure class="highlight abnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs abnf">let a <span class="hljs-operator">=</span> <span class="hljs-number">456</span><span class="hljs-comment">;</span><br>console.log(a)<span class="hljs-comment">;</span><br><br>export &#123;&#125;<br><br>/a是局部变量<br></code></pre></td></tr></table></figure>

<hr>
<h3 id="声明空间"><a href="#声明空间" class="headerlink" title="声明空间"></a>声明空间</h3><p>类型声明空间</p>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs delphi"><span class="hljs-keyword">type</span> A = <span class="hljs-keyword">string</span> <span class="hljs-comment">// A的类型是字符串</span><br></code></pre></td></tr></table></figure>

<p>变量声明空间</p>
<figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs nix"><span class="hljs-keyword">let</span> <span class="hljs-attr">a</span> = <span class="hljs-string">&quot;abc&quot;</span><br></code></pre></td></tr></table></figure>

<p>类型声明空间 和 变量声明空间 不能混着写：<code>let a = &quot;abc&quot; type B = a</code> ×  </p>
<p>特殊：类 — 类在TS中既是类型声明空间也是变量声明空间</p>
<figure class="highlight flix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs flix"><span class="hljs-keyword">class</span> Foo &#123;&#125;<br><span class="hljs-keyword">let</span> a = Foo<br><span class="hljs-keyword">type</span> B = Foo<br></code></pre></td></tr></table></figure>

<hr>
<h3 id="类型注解与类型推断"><a href="#类型注解与类型推断" class="headerlink" title="类型注解与类型推断"></a>类型注解与类型推断</h3><p>TS中通过 <code>类型注解</code> 将两个空间联系到一起</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs lasso"><span class="hljs-comment">//类型注解 --- 强制变量的类型</span><br><span class="hljs-keyword">let</span> a: <span class="hljs-built_in">string</span> = <span class="hljs-string">&quot;abc&quot;</span><br><br><span class="hljs-keyword">type</span> A = <span class="hljs-built_in">string</span><br><span class="hljs-keyword">let</span> a: A = <span class="hljs-string">&quot;abc&quot;</span><br><br><br><span class="hljs-comment">//类型推断 -- 自动完成类型注解的过程</span><br><span class="hljs-keyword">let</span> a = <span class="hljs-string">&quot;abc&quot;</span><br>a = <span class="hljs-number">123</span> <span class="hljs-comment">// 报错 ts自动类型推断 </span><br></code></pre></td></tr></table></figure>

<hr>
<h3 id="类型分类、联合类型、交叉类型"><a href="#类型分类、联合类型、交叉类型" class="headerlink" title="类型分类、联合类型、交叉类型"></a>类型分类、联合类型、交叉类型</h3><p>基本类型：<code>string number boolean null undefined symbol bigint</code></p>
<p>对象类型：<code>[] &#123;&#125; function()&#123;&#125;</code></p>
<p>TS新增类型：<code>any never void unknow enum</code></p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs csharp"><span class="hljs-keyword">let</span> a: <span class="hljs-built_in">string</span> = <span class="hljs-string">&quot;abc&quot;</span><br><br><span class="hljs-keyword">let</span> b: <span class="hljs-built_in">object</span> = [] <span class="hljs-comment">// object用的较少 直接针对数组、函数等</span><br><br></code></pre></td></tr></table></figure>

<p>联合类型：类型之间进行 或 的操作<br><code>let a: string | number= &quot;abc //支持字符串或数字&quot;</code> </p>
<p>交叉类型：类型之间进行 与 的操作 — 大多数用于对象中</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">type</span> A = &#123;<span class="hljs-attr">name</span>:<span class="hljs-built_in">string</span>&#125;<br><span class="hljs-keyword">type</span> B = &#123;<span class="hljs-attr">age</span>:<span class="hljs-built_in">number</span>&#125;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">a</span>: A|B = &#123;<span class="hljs-attr">name</span>:<span class="hljs-string">&quot;tom&quot;</span>&#125; <span class="hljs-comment">//联合类型 --- A、B包含一种即可</span><br><span class="hljs-keyword">let</span> <span class="hljs-attr">b</span>: A&amp;B = &#123;<span class="hljs-attr">name</span>:<span class="hljs-string">&quot;tom&quot;</span>,<span class="hljs-attr">age</span>:<span class="hljs-number">18</span>&#125; <span class="hljs-comment">// 交叉类型 必须既包含A又包含B</span><br></code></pre></td></tr></table></figure>



<p>any never void unknow enum：</p>
<p>never ：永不存在的值的类型（用的少）</p>
<p><code>let a: number &amp; string = 123  // a就是never类型</code></p>
<p>any：任意类型 — 不进行检测</p>
<p>unknow：any类型对应的安全类型 — 进行检测</p>
<hr>
<h3 id="类型断言、非空断言"><a href="#类型断言、非空断言" class="headerlink" title="类型断言、非空断言"></a>类型断言、非空断言</h3><p>听我的，ts不需要检测类型对不对</p>
<p>类型断言：当TS推断出来的类型不满足需求，需要手动指定一个类型(TS检测类型是否规范时的一个处理，当他最终编译后有问题还是会报错)</p>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs reasonml"><span class="hljs-keyword">let</span> a: unknow = <span class="hljs-string">&quot;abc&quot;</span><br>a = <span class="hljs-number">123</span><span class="hljs-function"></span><br><span class="hljs-function">(<span class="hljs-params">a</span> <span class="hljs-params">as</span> []).<span class="hljs-params">map</span>(<span class="hljs-params">()</span>=&gt;</span>&#123;&#125;)<br></code></pre></td></tr></table></figure>

<p>非空断言：</p>
<figure class="highlight arcade"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs arcade">let b: string | <span class="hljs-literal">undefined</span>= <span class="hljs-literal">undefined</span><br><br>b.<span class="hljs-built_in">length</span> <span class="hljs-comment">// 报错</span><br>b!.<span class="hljs-built_in">length</span> <span class="hljs-comment">// 告诉TS b 不是空的 所以只能是字符串 所以不会报错</span><br></code></pre></td></tr></table></figure>

<hr>
<h3 id="数组类型、元祖类型"><a href="#数组类型、元祖类型" class="headerlink" title="数组类型、元祖类型"></a>数组类型、元祖类型</h3><p>数组：</p>
<p><code>类型[] --- let a: (number|string)[] = [1,2,3,&quot;abc&quot;]</code></p>
<p><code>Array&lt;类型&gt; --- let a:Array&lt;number&gt; = [1,2,3]</code></p>
<p>元祖：允许表示一个已知元素数量和类型的数组，各元素的类型不必相同</p>
<p><code>let arr:[number,string] = [1,&quot;abc&quot;] //顺序、个数、类型都要一致</code></p>
<hr>
<h3 id="对象类型、索引签名"><a href="#对象类型、索引签名" class="headerlink" title="对象类型、索引签名"></a>对象类型、索引签名</h3><p>对象：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">type</span> A = &#123;<br>	<span class="hljs-attr">name</span>: <span class="hljs-built_in">string</span><br>	age?: <span class="hljs-built_in">number</span> <span class="hljs-comment">//age? -- 可选</span><br>&#125;<br><br><span class="hljs-keyword">let</span> <span class="hljs-attr">obj</span>: A = &#123;<br>	<span class="hljs-attr">name</span>: <span class="hljs-string">&quot;tom&quot;</span>,<br>	<span class="hljs-attr">age</span>: <span class="hljs-number">18</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>索引签名：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">type</span> A = &#123;<br>	<span class="hljs-attr">name</span>: <span class="hljs-built_in">string</span><br>	age?: <span class="hljs-built_in">number</span> <span class="hljs-comment">//age? -- 可选</span><br>	[<span class="hljs-attr">index</span>: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">any</span> <span class="hljs-comment">// 加上这个，下面的obj中可加入任何多余的字段</span><br>&#125;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">obj</span>: A = &#123;<br>	<span class="hljs-attr">name</span>: <span class="hljs-string">&quot;tom&quot;</span>,<br>	<span class="hljs-attr">age</span>: <span class="hljs-number">18</span>,<br>	<span class="hljs-attr">job</span>: <span class="hljs-string">&quot;aaa&quot;</span><br>&#125;<br><br><br><span class="hljs-keyword">type</span> B = &#123;<br>	[<span class="hljs-attr">index</span>:<span class="hljs-built_in">number</span>]: <span class="hljs-built_in">any</span> <span class="hljs-comment">// 数组建议用number</span><br>&#125;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">arr</span>: B = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-literal">true</span>,<span class="hljs-string">&quot;abc&quot;</span>]<br>arr[<span class="hljs-number">0</span>]<br></code></pre></td></tr></table></figure>

<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> <span class="hljs-attr">arr</span>:<span class="hljs-built_in">number</span>[] = []  <span class="hljs-comment">// 可以为空</span><br><br><span class="hljs-keyword">type</span> <span class="hljs-variable constant_">OBJ</span> = &#123;<span class="hljs-attr">name</span>: <span class="hljs-built_in">string</span>&#125;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">obj</span>: <span class="hljs-variable constant_">OBJ</span> = &#123;&#125;  × 不能为空<br><span class="hljs-keyword">let</span> obj = &#123;&#125; <span class="hljs-keyword">as</span> <span class="hljs-variable constant_">OBJ</span> √ 这种写法可以<br></code></pre></td></tr></table></figure>

<hr>
<h3 id="函数类型、void类型"><a href="#函数类型、void类型" class="headerlink" title="函数类型、void类型"></a>函数类型、void类型</h3><p>函数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// TS中要求实参的个数与形参个数相同</span><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">n: <span class="hljs-built_in">number</span>, m?<span class="hljs-built_in">string</span></span>): <span class="hljs-built_in">number</span>&#123;<br>	<span class="hljs-comment">// () : number   规定了返回值的类型</span><br>	<span class="hljs-keyword">return</span> <span class="hljs-number">123</span><br>&#125;<br><br><span class="hljs-title function_">foo</span>(<span class="hljs-number">123</span>)<br><span class="hljs-title function_">foo</span>(<span class="hljs-number">123</span>,<span class="hljs-string">&quot;abc&quot;</span>)<br><br><span class="hljs-keyword">let</span> <span class="hljs-attr">foo</span>: <span class="hljs-function">(<span class="hljs-params">n: <span class="hljs-built_in">number</span>, m: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">number</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">n,m</span>)&#123;<br>	<span class="hljs-keyword">return</span> <span class="hljs-number">123</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>void: 表示函数没有任何返回值的类型</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">let</span> foo = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>): <span class="hljs-keyword">void</span>&#123; <span class="hljs-comment">//可以不return 也可以return undefined</span><br><br>&#125;<br><br><span class="hljs-keyword">let</span> <span class="hljs-attr">foo</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">void</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<hr>
<h3 id="函数重载与可调用注解"><a href="#函数重载与可调用注解" class="headerlink" title="函数重载与可调用注解"></a>函数重载与可调用注解</h3><p>函数重载是指函数约束传入不同的参数，返回不同类型的数据，而且可以清晰的知道传入不同的参数得到不同的结果</p>
<figure class="highlight fortran"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs fortran"><span class="hljs-function"><span class="hljs-keyword">function</span></span> foo(n1: <span class="hljs-keyword">number</span>): <span class="hljs-built_in">any</span><br><span class="hljs-function"><span class="hljs-keyword">function</span></span> foo(n1: <span class="hljs-keyword">number</span>, n2:<span class="hljs-keyword">number</span>): <span class="hljs-built_in">any</span><br><span class="hljs-function"><span class="hljs-keyword">function</span></span> foo(n1: <span class="hljs-keyword">number</span>, n2:<span class="hljs-keyword">number</span>, n3:<span class="hljs-keyword">number</span>): <span class="hljs-built_in">any</span><br><span class="hljs-function"><span class="hljs-keyword">function</span></span> foo(n1: <span class="hljs-keyword">number</span>, n2?: <span class="hljs-keyword">number</span>, n3?: <span class="hljs-keyword">number</span>)&#123;<br><br>&#125;<br><br>foo(<span class="hljs-number">1</span>)<br>foo(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>)<br>foo(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)<br>foo(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>)  ×<br></code></pre></td></tr></table></figure>

<p>可调用注解：函数和类的另一种写法</p>
<p>函数重载想用类型注解必须用可调用注解</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">type</span> A = &#123;<br>	(): <span class="hljs-built_in">void</span><br>&#125;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">a</span>: A = <span class="hljs-function">() =&gt;</span>&#123;&#125;<br><br><br><span class="hljs-keyword">type</span> A = &#123;<br>	(<span class="hljs-attr">n1</span>: <span class="hljs-built_in">number</span>): <span class="hljs-built_in">any</span><br>	(<span class="hljs-attr">n1</span>: <span class="hljs-built_in">number</span>, <span class="hljs-attr">n2</span>:<span class="hljs-built_in">number</span>): <span class="hljs-built_in">any</span><br>	(<span class="hljs-attr">n1</span>: <span class="hljs-built_in">number</span>, <span class="hljs-attr">n2</span>:<span class="hljs-built_in">number</span>, <span class="hljs-attr">n3</span>:<span class="hljs-built_in">number</span>): <span class="hljs-built_in">any</span><br>&#125;<br><span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">n1: <span class="hljs-built_in">number</span></span>): <span class="hljs-built_in">any</span><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">n1: <span class="hljs-built_in">number</span>, n2:<span class="hljs-built_in">number</span></span>): <span class="hljs-built_in">any</span><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">n1: <span class="hljs-built_in">number</span>, n2:<span class="hljs-built_in">number</span>, n3:<span class="hljs-built_in">number</span></span>): <span class="hljs-built_in">any</span><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">n1: <span class="hljs-built_in">number</span>, n2?: <span class="hljs-built_in">number</span>, n3?: <span class="hljs-built_in">number</span></span>)&#123;<br><br>&#125;<br><br><span class="hljs-title function_">foo</span>(<span class="hljs-number">1</span>)<br><span class="hljs-title function_">foo</span>(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>)<br><span class="hljs-title function_">foo</span>(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)<br></code></pre></td></tr></table></figure>

<hr>
<h3 id="枚举类型、const枚举"><a href="#枚举类型、const枚举" class="headerlink" title="枚举类型、const枚举"></a>枚举类型、const枚举</h3><p>枚举是组织收集有关联集合的一种方式，是代码更加易于阅 读</p>
<p>枚举是只读的（一些常量）</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs stylus"><span class="hljs-comment">//自动累加</span><br>enum Roles&#123;<br>	SUPER_ADMIN,<br>	ADMIN,<br>	USER<br>&#125;<br>console<span class="hljs-selector-class">.log</span>(Roles.SUPER_ADMIN) <span class="hljs-comment">// 0</span><br>console<span class="hljs-selector-class">.log</span>(Roles.ADMIN) <span class="hljs-comment">// 1</span><br>console<span class="hljs-selector-class">.log</span>(Roles.USER) <span class="hljs-comment">// 2</span><br><br><br>enum Roles&#123;<br>	SUPER_ADMIN,<br>	ADMIN = <span class="hljs-number">3</span>,<br>	USER<br>&#125;<br>console<span class="hljs-selector-class">.log</span>(Roles.SUPER_ADMIN) <span class="hljs-comment">// 0</span><br>console<span class="hljs-selector-class">.log</span>(Roles.ADMIN) <span class="hljs-comment">// 3</span><br>console<span class="hljs-selector-class">.log</span>(Roles.USER) <span class="hljs-comment">// 4</span><br><br><span class="hljs-comment">// 映射</span><br>enum Roles&#123;<br>	SUPER_ADMIN,<br>	ADMIN = <span class="hljs-number">3</span>,<br>	USER<br>&#125;<br>console<span class="hljs-selector-class">.log</span>(Roles.<span class="hljs-selector-attr">[0]</span>) <span class="hljs-comment">//</span><br>console<span class="hljs-selector-class">.log</span>(Roles.<span class="hljs-selector-attr">[3]</span>) <span class="hljs-comment">//</span><br>console<span class="hljs-selector-class">.log</span>(Roles.<span class="hljs-selector-attr">[4]</span>) <span class="hljs-comment">//</span><br><br><span class="hljs-comment">//语义化</span><br>enum Roles&#123;<br>	SUPER_ADMIN,<br>	ADMIN = <span class="hljs-number">3</span>,<br>	USER<br>&#125;<br><span class="hljs-function"><span class="hljs-title">if</span><span class="hljs-params">(role === <span class="hljs-number">0</span>)</span></span>&#123;<br> <span class="hljs-comment">// 如果是超级管理员 .....</span><br>&#125;<br><span class="hljs-function"><span class="hljs-title">if</span><span class="hljs-params">(role === SUPER_ADMIN)</span></span>&#123;<br> <span class="hljs-comment">// 如果是超级管理员 .....</span><br>&#125;<br><br></code></pre></td></tr></table></figure>

<p>const枚举：编译后可提升性能（不会转化为对象）</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E7%AC%94%E8%AE%B0/" class="category-chain-item">笔记</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/TS/">#TS</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>TS基础</div>
      <div>https://dl_coisini.gitee.io/2023/09/25/TS基础/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>d-lue</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年9月25日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/09/28/TS%E8%BF%9B%E9%98%B6/" title="TS进阶">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">TS进阶</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/09/19/JavaScript%E7%AC%94%E8%AE%B0(%E4%BA%8C)/" title="JavaScript笔记（二）">
                        <span class="hidden-mobile">JavaScript笔记（二）</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body>
</html>
